<template>
  <div class="student-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="班级" class="search-item">
          <el-select
            v-model="searchForm.clazzId"
            placeholder="请选择班级"
            clearable
            filterable
            class="search-select"
          >
            <el-option
              v-for="clazz in clazzOptions"
              :key="clazz.id"
              :label="clazz.name"
              :value="clazz.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学历" class="search-item">
          <el-select
            v-model="searchForm.degree"
            placeholder="请选择学历"
            clearable
            class="search-select"
          >
            <el-option
              v-for="degree in degreeOptions"
              :key="degree.value"
              :label="degree.label"
              :value="degree.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="姓名" class="search-item">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            clearable
            class="search-input"
          />
        </el-form-item>

        <el-form-item class="search-item">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增学员
      </el-button>
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
        <el-icon><Delete /></el-icon>批量删除
      </el-button>
    </div>

    <!-- 学员列表 -->
    <el-card class="table-card">
      <el-table
        :data="studentList"
        border
        stripe
        @selection-change="handleSelectionChange"
        v-loading="loading"
        class="student-table"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <!-- 序号列 -->
        <el-table-column label="序号" width="60" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (pagination.current - 1) * pagination.size + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="no" label="学号" width="120" align="center" />
        <el-table-column prop="name" label="姓名" width="100" align="center" />
        <el-table-column label="性别" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.gender === 1 ? '' : 'danger'">
              {{ row.gender === 1 ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130" align="center" />
        <!-- 身份证号脱敏展示 -->
        <el-table-column label="身份证号" width="180" align="center">
          <template #default="{ row }">
            <el-tooltip :content="row.idCard" placement="top" v-if="row.idCard">
              <span>
                {{ row.idCard.substring(0, 6) }}****{{
                  row.idCard.substring(row.idCard.length - 4)
                }}
              </span>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- 学历显示 -->
        <el-table-column label="学历" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getDegreeTagType(row.degree)" class="degree-tag">
              {{ getDegreeLabel(row.degree) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="clazzName" label="班级" width="150" align="center" />
        <!-- 违规分数显示 -->
        <el-table-column label="违规分数" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.violationScore > 0 ? 'danger' : 'success'">
              {{ row.violationScore }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 最后修改时间 -->
        <el-table-column label="最后修改时间" width="180" align="center">
          <template #default="{ row }">
            <div class="update-time">
              <el-icon><Clock /></el-icon>
              <span>{{ formatDateTime(row.updateTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="250" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" class="action-btn">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="openViolationDialog(row)"
              class="action-btn"
            >
              <el-icon><Document /></el-icon>违规处理
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)" class="action-btn">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        class="pagination"
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 学生表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑学员信息' : '新增学员'"
      width="650px"
      class="student-form-dialog"
    >
      <el-form
        ref="studentFormRef"
        :model="studentForm"
        :rules="rules"
        label-width="100px"
        label-position="top"
      >
        <div class="form-row">
          <el-form-item label="姓名" prop="name" class="form-item">
            <el-input v-model="studentForm.name" placeholder="请输入姓名" />
          </el-form-item>

          <el-form-item label="学号" prop="no" class="form-item">
            <el-input v-model="studentForm.no" placeholder="请输入学号" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="性别" prop="gender" class="form-item">
            <el-radio-group v-model="studentForm.gender">
              <el-radio :label="Gender.MALE">男</el-radio>
              <el-radio :label="Gender.FEMALE">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="是否院校" prop="isCollege" class="form-item">
            <el-radio-group v-model="studentForm.isCollege">
              <el-radio :label="CollegeFlag.IS_COLLEGE">是</el-radio>
              <el-radio :label="CollegeFlag.NOT_COLLEGE">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="手机号" prop="phone" class="form-item">
            <el-input v-model="studentForm.phone" placeholder="请输入手机号" />
          </el-form-item>

          <el-form-item label="身份证号" prop="idCard" class="form-item">
            <el-input v-model="studentForm.idCard" placeholder="请输入身份证号" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="学历" prop="degree" class="form-item">
            <el-select
              v-model="studentForm.degree"
              placeholder="请选择学历"
              style="width: 100%"
              class="degree-select"
            >
              <el-option
                v-for="degree in degreeOptions"
                :key="degree.value"
                :label="degree.label"
                :value="degree.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="毕业时间" prop="graduationDate" class="form-item">
            <el-date-picker
              v-model="studentForm.graduationDate"
              type="date"
              placeholder="选择毕业日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="班级" prop="clazzId" class="form-item">
            <el-select
              v-model="studentForm.clazzId"
              placeholder="请选择班级"
              style="width: 100%"
              class="clazz-select"
            >
              <el-option
                v-for="clazz in clazzOptions"
                :key="clazz.id"
                :label="clazz.name"
                :value="clazz.id"
              />
            </el-select>
          </el-form-item>

          <!-- 编辑时显示违规分数 -->
          <el-form-item v-if="isEdit" label="违规分数" class="form-item">
            <el-input-number
              v-model="studentForm.violationScore"
              :min="0"
              :max="100"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </div>

        <el-form-item label="联系地址" prop="address" class="form-item">
          <el-input
            v-model="studentForm.address"
            type="textarea"
            placeholder="请输入联系地址"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">
          <el-icon><Close /></el-icon>取消
        </el-button>
        <el-button type="primary" @click="submitForm">
          <el-icon><Check /></el-icon>确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 违规处理对话框 -->
    <el-dialog
      v-model="violationDialogVisible"
      title="违规处理"
      width="400px"
      class="violation-dialog"
    >
      <el-form :model="violationForm" label-width="80px">
        <el-form-item label="学生姓名">
          <el-input v-model="violationForm.studentName" disabled />
        </el-form-item>
        <el-form-item label="当前分数">
          <el-input v-model="violationForm.currentScore" disabled />
        </el-form-item>
        <el-form-item label="违规分数" prop="score" required>
          <el-input-number
            v-model="violationForm.score"
            :min="0"
            :max="100"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="处理说明">
          <el-input
            v-model="violationForm.reason"
            type="textarea"
            placeholder="请输入违规原因和处理说明"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="violationDialogVisible = false">
          <el-icon><Close /></el-icon>取消
        </el-button>
        <el-button type="primary" @click="handleViolationSubmit">
          <el-icon><Check /></el-icon>提交处理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import dayjs from 'dayjs'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Edit,
  Clock,
  Close,
  Check,
  Document,
} from '@element-plus/icons-vue'
import {
  queryPageApi,
  addApi,
  updateApi,
  deleteApi,
  queryClazzListApi,
  handleViolationApi,
  type StudentModel,
  type StudentQueryParams,
  type PageResultModel,
  type ResultModel,
  type ClazzModel,
  type ViolationHandleParams,
  Gender,
  DegreeType,
  CollegeFlag,
} from '@/api/stu'

// 搜索表单
const searchForm = reactive<StudentQueryParams>({
  clazzId: null,
  degree: null,
  name: '',
  page: 1,
  pageSize: 10,
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
})

// 学员列表
const studentList = ref<StudentModel[]>([])
const selectedRows = ref<StudentModel[]>([])
const loading = ref(false)

// 学历选项
const degreeOptions = [
  { value: DegreeType.JUNIOR, label: '初中' },
  { value: DegreeType.HIGH_SCHOOL, label: '高中' },
  { value: DegreeType.COLLEGE, label: '大专' },
  { value: DegreeType.BACHELOR, label: '本科' },
  { value: DegreeType.MASTER, label: '硕士' },
  { value: DegreeType.DOCTOR, label: '博士' },
]

// 班级选项（从API获取）
const clazzOptions = ref<ClazzModel[]>([])

// 表单相关
const dialogVisible = ref(false)
const violationDialogVisible = ref(false)
const isEdit = ref(false)
const studentFormRef = ref<FormInstance>()
const currentStudent = ref<StudentModel | null>(null)

// 学生表单
const studentForm = reactive<Partial<StudentModel>>({
  name: '',
  no: '',
  gender: Gender.MALE,
  phone: '',
  idCard: '',
  isCollege: CollegeFlag.IS_COLLEGE,
  address: '',
  degree: undefined,
  graduationDate: '',
  clazzId: undefined,
  violationScore: 0,
})

// 违规处理表单
const violationForm = reactive({
  studentId: 0,
  studentName: '',
  currentScore: 0,
  score: 0,
  reason: '',
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  no: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '身份证号格式不正确',
      trigger: 'blur',
    },
  ],
  clazzId: [{ required: true, message: '请选择班级', trigger: 'change' }],
})

// 获取学历标签
const getDegreeLabel = (degree?: number | null) => {
  if (!degree) return '-'
  const degreeOption = degreeOptions.find((opt) => opt.value === degree)
  return degreeOption ? degreeOption.label : '-'
}

// 获取学历标签类型（用于不同颜色）
const getDegreeTagType = (degree?: number | null) => {
  if (!degree) return 'info'
  if (degree >= DegreeType.BACHELOR) return 'success'
  if (degree === DegreeType.COLLEGE) return 'warning'
  return 'info'
}

// 格式化时间
const formatDateTime = (dateString?: string) => {
  if (!dateString) return '-'
  return dayjs(dateString).format('YYYY-MM-DD HH:mm')
}

// 获取班级列表
const fetchClazzList = async () => {
  try {
    const response: ResultModel<ClazzModel[]> = await queryClazzListApi()
    if (response.code === 1) {
      clazzOptions.value = response.data
    } else {
      ElMessage.error(`获取班级列表失败: ${response.msg}`)
    }
  } catch (error) {
    console.error('获取班级列表出错:', error)
    ElMessage.error('获取班级列表失败')
  }
}

// 获取学员列表
const fetchStudents = async () => {
  try {
    loading.value = true
    const params: StudentQueryParams = {
      name: searchForm.name,
      degree: searchForm.degree,
      clazzId: searchForm.clazzId,
      page: pagination.current,
      pageSize: pagination.size,
    }

    const response: PageResultModel<StudentModel> = await queryPageApi(params)
    if (response.code === 1) {
      studentList.value = response.data.rows
      pagination.total = response.data.total
    } else {
      console.error('获取学员列表失败:', response.msg)
    }
  } catch (error) {
    console.error('获取学员列表出错:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchStudents()
}

// 重置搜索
const resetSearch = () => {
  searchForm.clazzId = null
  searchForm.degree = null
  searchForm.name = ''
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchStudents()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchStudents()
}

// 表格选择变化
const handleSelectionChange = (rows: StudentModel[]) => {
  selectedRows.value = rows
}

// 新增学员
const handleAdd = () => {
  isEdit.value = false
  Object.assign(studentForm, {
    name: '',
    no: '',
    gender: Gender.MALE,
    phone: '',
    idCard: '',
    isCollege: CollegeFlag.IS_COLLEGE,
    address: '',
    degree: undefined,
    graduationDate: '',
    clazzId: undefined,
    violationScore: 0,
  })
  dialogVisible.value = true
}

// 编辑学员
const handleEdit = (student: StudentModel) => {
  isEdit.value = true
  currentStudent.value = student
  Object.assign(studentForm, {
    ...student,
    violationScore: student.violationScore || 0,
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!studentFormRef.value) return

  try {
    await studentFormRef.value.validate()

    const formData = {
      ...studentForm,
      violationScore: studentForm.violationScore || 0,
    }

    if (isEdit.value) {
      // 编辑学员 - 调用更新API
      const response: ResultModel = await updateApi(formData as StudentModel)
      if (response.code === 1) {
        ElMessage.success('学员信息更新成功')
        dialogVisible.value = false
        fetchStudents()
      } else {
        ElMessage.error(`更新失败: ${response.msg}`)
      }
    } else {
      // 新增学员 - 调用新增API
      const response: ResultModel<number> = await addApi(formData as Omit<StudentModel, 'id'>)
      if (response.code === 1) {
        ElMessage.success(`学员添加成功，ID: ${response.data}`)
        dialogVisible.value = false
        fetchStudents()
      } else {
        ElMessage.error(`添加失败: ${response.msg}`)
      }
    }
  } catch (error) {
    console.error('表单提交失败:', error)
  }
}

// 删除学员
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该学员吗？', '警告', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })

    const response: ResultModel = await deleteApi([id])
    if (response.code === 1) {
      ElMessage.success('学员删除成功')
      fetchStudents()
    } else {
      ElMessage.error(`删除失败: ${response.msg}`)
    }
  } catch (error) {
    console.log('删除操作已取消')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) return

  try {
    const ids = selectedRows.value.map((row) => row.id)
    await ElMessageBox.confirm(`确定要删除选中的 ${ids.length} 位学员吗？', '警告`, {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })

    const response: ResultModel = await deleteApi(ids)
    if (response.code === 1) {
      ElMessage.success(`成功删除 ${ids.length} 位学员`)
      selectedRows.value = []
      fetchStudents()
    } else {
      ElMessage.error(`批量删除失败: ${response.msg}`)
    }
  } catch (error) {
    console.log('批量删除操作已取消')
  }
}

// 打开违规处理对话框
const openViolationDialog = (student: StudentModel) => {
  Object.assign(violationForm, {
    studentId: student.id,
    studentName: student.name,
    currentScore: student.violationScore || 0,
    score: student.violationScore || 0,
    reason: '',
  })
  violationDialogVisible.value = true
}

// 提交违规处理
const handleViolationSubmit = async () => {
  try {
    const params: ViolationHandleParams = {
      id: violationForm.studentId,
      score: violationForm.score,
    }

    const response: ResultModel = await handleViolationApi(params)
    if (response.code === 1) {
      ElMessage.success('违规处理成功')
      violationDialogVisible.value = false
      fetchStudents()
    } else {
      ElMessage.error(`违规处理失败: ${response.msg}`)
    }
  } catch (error) {
    console.error('提交违规处理出错:', error)
    ElMessage.error('违规处理提交失败')
  }
}

// 初始化加载数据
onMounted(() => {
  fetchStudents()
  fetchClazzList()
})
</script>

<style scoped lang="scss">
.student-management {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .search-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .search-item {
      margin-right: 20px;
      margin-bottom: 15px;

      &:last-child {
        margin-right: 0;
      }
    }

    .search-select {
      width: 180px;
    }

    .search-input {
      width: 180px;
    }
  }
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .student-table {
    font-size: 14px;

    :deep(.el-table__header) th {
      background-color: #f8f9fa;
      font-weight: bold;
    }

    .degree-tag {
      min-width: 50px;
      text-align: center;
      font-weight: bold;
    }

    .update-time {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 5px;

      .el-icon {
        color: #909399;
      }
    }

    .action-btn {
      padding: 5px 8px;
      margin: 2px;
      display: inline-flex;
      align-items: center;
      font-size: 12px;

      .el-icon {
        margin-right: 3px;
        font-size: 14px;
      }
    }
  }
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.student-form-dialog {
  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;

    .form-item {
      flex: 1;
      margin-bottom: 0;
    }
  }

  .degree-select,
  .clazz-select {
    :deep(.el-input__inner) {
      height: 40px;
    }
  }
}

.violation-dialog {
  .el-form-item {
    margin-bottom: 18px;
  }
}
</style>
